import {
  getConferencesExtendFields
} from '@/api/zzxt/party-conference/confer-extend-fields'
import { companyConferList } from '@/api/zzxt/party-conference/confer'
import store from '@/store'
let extendFieldsDict = null
export function loadConference(query) {
  return new Promise((res, rej) => {
    const result = {}
    companyConferList(query).then(data => {
      const list = data.list
      const confersDict = {}
      list.map(i => {
        confersDict[i.id] = i
      })
      result.totalCount = data.totalCount
      result.host = (list.find(i => i.host) || {}).userId // 返回任意一项的主持人
      getConferencesExtendFields({ conferences: list.map(i => i.id) }).then(
        data => {
          data.list.map(field => {
            const { conference, type } = field
            const extendFieldType = extendFieldsDict[type]
            const { name } = extendFieldType
            confersDict[conference][name] = field.value[0] // TODO 此处应判断是否真的不是数组类型
          })
          result.conferences = list
          return res(result)
        }
      )
    })
  })
}

export default (query) => {
  return new Promise((res, rej) => {
    const runOnce = () => {
      extendFieldsDict = store.state.party.conferenceExtendFieldDict
      if (!extendFieldsDict) return setTimeout(() => { runOnce() }, 2e2)
      loadConference(query).then(data => res(data)).catch(e => rej(e))
    }
    runOnce()
  })
}
